package com.bob.clan.wxconnector.wxService;

import com.bob.clan.wxconnector.component.MpComponent;
import com.bob.clan.wxconnector.config.WxServerConfig;
import com.bob.clan.wxconnector.entity.Fans;
import com.bob.clan.wxconnector.entity.Mp;
import com.bob.clan.wxconnector.exception.MpException;
import com.bob.clan.wxconnector.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class TokenService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MpComponent mpComponent;
    @Autowired
    private WxServerConfig wxServerConfig;

    //返回指定系统当前的token值
    public String getToken(String sysCode){
        //直接从redis缓存里取,key:wx_sysCode_token
        if(verifySysCode(sysCode)){
            String token = redisTemplate.opsForValue().get("wx_"+sysCode+"_token");
            if(token == null){
                updateRedisToken();
            }
            return redisTemplate.opsForValue().get("wx_"+sysCode+"_token");
        }else{
            throw new RuntimeException(sysCode +"：该sysCode不存在，请填写正确值");
        }
    }

    private boolean verifySysCode(String sysCode){
       return mpComponent.getBySysCode(sysCode)==null?false:true;
    }

    //供定时器调整调用，为每个服务号生成token
    public void updateRedisToken() {
        List<Mp> mpList = mpComponent.getListSingleOriginalId();
        for (Mp mp : mpList) {
            try {
                String mpToken = this.getTokenFromWechat(mp);
                //当前系统里，允许一个original对应多个sysCode
                List<Mp> sameOriginalIdMp = mpComponent.getListByOriginalId(mp.getOriginalId());
                for (Mp codeMp : sameOriginalIdMp) {
                    String token_key = "wx_"+codeMp.getSysCode()+"_token";
                    redisTemplate.opsForValue().set(token_key, mpToken, 2, TimeUnit.HOURS);
                    log.info(token_key+"===Redis value updated: " + mpToken);
                }
            } catch (MpException e) {
                throw new RuntimeException(e);
            }
        }
    }

    //组装报文，向微信平台获取token
    private String getTokenFromWechat(Mp mp) throws MpException {
        String tokenUrl = wxServerConfig.getMpAccessTokenUrl(mp);
        String respXML = HttpUtil.reqJsonGet(tokenUrl);
        log.info("update base server token, get respXML=" + respXML);
        JSONObject retJO = JSONObject.fromObject(respXML);
        return retJO.getString("access_token");
    }
}
